const express = require("express");
const multer = require("multer");
const cors = require("cors");
const path = require('path');
const port = 4060;

const app = express();
app.use(cors());
const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, "./files");
  },

  filename: (req, file, cb) => {
    // fieldname 是表单的name值，也就是我们设定的“avatar”，
    // originalname是文件上传时的名字，可以根据它获取后缀，
    // encoding，mimetype 我就不详细介绍了，可以自行输出查看。 encoding: '7bit',  mimetype: 'image/jpeg',
    const { fieldname, originalname, encoding, mimetype } = file;

    const arr = originalname.split(".");
    const after = arr[arr.length - 1] ? "." + arr[arr.length - 1] : ".jpg";
    console.log("after", after);
    cb(null, arr[0] + after);
  },
});
const upload = multer({ storage });
app.use('/public', express.static(path.join(__dirname, 'files'))); // 映射静态资源目录‌:ml-citation{ref="7" data="citationList"}


app.get("/", (req, res) => {
  res.send("nodejs测试");
});
app.post("/upload", upload.single("avatar"), (req, res, next) => {
  //   console.log("req.file", req.file);
  console.log("req.body", req.body);

  const fileUrl = `${req.protocol}://${req.get('host')}/public/${req.file.filename}`;
  res.json({ code: 200, url: fileUrl });
});
app.listen(port, () => {
  console.log("监听端口:" + port);
});

